﻿using AutoMapper;
using Common;
using DB.Model;
using DB.Model.Input;
using DB.Model.OutPut;
using DB.MongoDB;
using DB.MongoDB.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NoticeWechat.Controllers
{
    [Authorize]
    public class NodesController : ApiController
    {
        IMongoDbHelper<Nodes> _Db; IMapper _mapper;
        public NodesController(IMongoDbHelper<Nodes> mongoDb, IMapper mapper)
        {
            _Db = mongoDb; _mapper = mapper;
        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<AjaxResult> HeartBeat(NodesInput NodeInput)
        {
            var Node = _mapper.Map<Nodes>(NodeInput);
            Node.Heartbeat = DateTime.Now;
            Node.State = 1;
            var one = _Db.AsQueryable().Where(x => x.NodeName == Node.NodeName).FirstOrDefault();
            if (one != null)
            {
                Node.Id = one.Id;
                await _Db.Update(Node);
                return new AjaxResult() { Message = "更新成功", Type = ResultType.Success };
            }
            await _Db.Insert(Node);
            return new AjaxResult() { Message = "新增成功", Type = ResultType.Success };
        }

        [HttpPost]
        public async Task<AjaxResult> Delete(string id)
        {
            await _Db.Delete(id);
            return new AjaxResult() { Message = "删除成功", Type = ResultType.Success };
        }
         
        [HttpPost]
        public async Task<List<NodesOutput>> QueryAll(FilterGroup Input)
        {
            var uid = User.Identity.GetUserId();
            Input.FilterRules.Add(new FilterRule("UserId", uid));
            var result = await _Db.QueryFilter(Input);
            var list = _mapper.ProjectTo<NodesOutput>(result.AsQueryable());
            return list.OrderBy(x => x.Heartbeat).ToList();
        }
    }
}
